#include <iostream>
#include <vector>
#include <queue>
#include <string>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

// 从层序遍历构建二叉树
TreeNode* buildTree(const vector<string>& nodes) {
    if (nodes.empty() || nodes[0] == nullptr) return nullptr;
    queue<TreeNode*> q;
    TreeNode* root = new TreeNode(nodes[0]);
    q.push(root);
    int i = 1;
    while (!q.empty() && i < nodes.size()) {
        TreeNode* node = q.front();
        q.pop();
        if (i < nodes.size() && nodes[i] != nullptr) {
            node->left = new TreeNode(nodes[i]);
            q.push(node->left);
        }
        ++i;
        if (i < nodes.size() && nodes[i] != nullptr) {
            node->right = new TreeNode(nodes[i]);
            q.push(node->right);
        }
        ++i;
    }
    return root;
}

class Solution {
public:
    vector<string> rightSideView(TreeNode* root) {
        vector<string> result;
        if (!root) return result;
        
        queue<TreeNode*> q;
        q.push(root);
        
        while (!q.empty()) {
            int levelSize = q.size();
            for (int i = 0; i < levelSize; ++i) {
                TreeNode* node = q.front();
                q.pop();
                
                if (i == levelSize - 1) {
                    result.push_back(node->val);
                }
                
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
        }
        
        return result;
    }
};

int main() {
    vector<string> nodes = {1, 2, 3, nullptr, 5, nullptr, 4};
    TreeNode* root = buildTree(nodes);
    Solution solution;
    vector<string> view = solution.rightSideView(root);
    
    for (int val : view) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}